﻿#region header

//  ***************************************************************************
// *                                LICENSE
//  ***************************************************************************
//  * "Haplous" .NET Simple 2D Game Framework
//  * 
//  * Copyright © Jonathan Evans 2014-2014
//  * 
//  * This program is free software; you can redistribute it and/or
//  * modify it under the terms of the GNU General Public License
//  * as published by the Free Software Foundation; either version 2
//  * of the License, or (at your option) any later version.
//  * 
//  * This program is distributed in the hope that it will be useful,
//  * but WITHOUT ANY WARRANTY; without even the implied warranty of
//  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  * GNU General Public License for more details.
//  * 
//  * You should have received a copy of the GNU General Public License
//  * along with this program; if not, write to the Free Software
//  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//  * 
//  ***************************************************************************
//  * 
//  * Contact: opencollar@googlemail.com
//  * 
//  * Website: http://haplous.codeplex.com/
//  *
//  * NuGet:   http://www.nuget.org/packages/haplous/
//  *
//  * File:    Haplous/Haplous/Position.cs
//  *
//  ***************************************************************************

#endregion

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;

using Haplous.Core;

using JetBrains.Annotations;

namespace Haplous
{
    /// <summary>
    ///     A class representing a pair of coordinates.
    /// </summary>
    /// <typeparam name="T">The type in which each coordinate is stored.</typeparam>
    [DebuggerDisplay("Position: {X},{Y}")]
    public class Position<T> : DisposableNotifyObject where T : struct
    {
        /// <summary>
        ///     An event used to signal that the current update has completed.
        /// </summary>
        [NotNull]
        private readonly AutoResetEvent _lockedForUpdateEvent = new AutoResetEvent(true);

        /// <summary>
        ///     The _locked for update lock
        /// </summary>
        [NotNull]
        private readonly object _lockedForUpdateLock = new object();

        /// <summary>
        ///     Indicates that this object cannot be changed externally.
        /// </summary>
        private bool _isLocked;

        /// <summary>
        ///     A flag used to control whether anything can change this object during an update.
        /// </summary>
        private volatile bool _lockedForUpdate;

        /// <summary>
        ///     The horizontal coordinate.
        /// </summary>
        private T _x;

        /// <summary>
        ///     The vertical coordinate.
        /// </summary>
        private T _y;

        /// <summary>
        ///     Initializes a new instance of the <see cref="Position{T}" /> class.
        /// </summary>
        /// <param name="x">The horizontal coordinate measured in pixels from the left border.</param>
        /// <param name="y">The vertical coordinate measured in pixels from the top border.</param>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")]
        public Position(T x, T y)
        {
            _x = x;
            _y = y;
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="Position{T}" /> class.
        /// </summary>
        public Position()
        {}

        /// <summary>
        ///     Indicates that this object cannot be changed externally.
        /// </summary>
        /// <remarks>Whilst locked this property can only be changed by the <see cref="Director" /> of an <see cref="Actor" />.</remarks>
        public bool IsLocked
        {
            get { return _isLocked; }
            internal set { _isLocked = value; }
        }

        /// <summary>
        ///     The horizontal coordinate measured in pixels from the left border.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "X")]
        public T X
        {
            get { return _x; }
            set
            {
                if(_isLocked)
                    throw new LockedException("This object is locked.  Changes may only be made by the director.");

                if(_lockedForUpdate)
                    throw new LockedException("This object is locked for update - nothing is permitted to change it until the moving object has finished.");

                OnPropertyChanged("X", ref _x, value);
            }
        }

        /// <summary>
        ///     The vertical coordinate measured in pixels from the top border.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Y")]
        public T Y
        {
            get { return _y; }
            set
            {
                if(_isLocked)
                    throw new LockedException("This object is locked.  Changes may only be made by the controller.");

                if(_lockedForUpdate)
                    throw new LockedException("This object is locked for update - nothing is permitted to change it until the moving object has finished.");
                OnPropertyChanged("Y", ref _y, value);
            }
        }

        /// <summary>
        ///     Gets a value indicating whether this instance is locked for update by a director .
        /// </summary>
        /// <value><see langword="true" /> if this instance is locked for update; otherwise, <see langword="false" />.</value>
        public bool IsLockedForUpdate
        {
            get { return _lockedForUpdate; }
        }

        /// <summary>
        ///     Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing">
        ///     <see langword="true" /> to release both managed and unmanaged resources;
        ///     <see langword="false" /> to release only unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if(disposing)
                _lockedForUpdateEvent.Dispose();

            base.Dispose(disposing);
        }

        /// <summary>
        ///     Sets the specified coordinates.
        /// </summary>
        /// <param name="x">The horizontal coordinate measured in pixels from the left border.</param>
        /// <param name="y">The vertical coordinate measured in pixels from the top border.</param>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")]
        public void Set(T x, T y)
        {
            if(_isLocked)
                throw new LockedException("This object is locked.  Changes may only be made by the controller.");

            if(_lockedForUpdate)
                throw new LockedException("This object is locked for update - nothing is permitted to change it until the moving object has finished.");

            var xChanged = !Equals(x, _x);
            if(xChanged)
                _x = x;

            var yChanged = !Equals(y, _y);
            if(yChanged)
                _y = y;

            if(xChanged)
                OnPropertyChanged("X");
            if(yChanged)
                OnPropertyChanged("Y");
        }

        /// <summary>
        ///     Locks this instance, preventing updates until the <see cref="FinishDirectorUpdate" /> method is called.
        /// </summary>
        public void StartDirectorUpdate()
        {
            if(_lockedForUpdate)
                return;

            lock(_lockedForUpdateLock)
            {
                if(_lockedForUpdate)
                    return;

                _lockedForUpdateEvent.Reset();
                _lockedForUpdate = true;
            }
        }

        /// <summary>
        ///     Waits for an update by a director to complete.
        /// </summary>
        public void WaitForDirectorUpdate()
        {
            if(!_lockedForUpdate)
                return;

            lock(_lockedForUpdateLock)
            {
                if(!_lockedForUpdate)
                    return;
            }

            _lockedForUpdateEvent.WaitOne();
        }

        /// <summary>
        ///     Unlocks this instance, allowing updates, allows threads waiting in the <see cref="WaitForDirectorUpdate" /> method
        ///     to proceed.
        /// </summary>
        public void FinishDirectorUpdate()
        {
            if(!_lockedForUpdate)
                return;

            lock(_lockedForUpdateLock)
            {
                if(!_lockedForUpdate)
                    return;

                _lockedForUpdateEvent.Set();
                _lockedForUpdate = false;
            }
        }

        /// <summary>
        ///     Sets the x and y from the specified <see cref="T:Position" /> object.
        /// </summary>
        /// <param name="newPosition">
        ///     The <see cref="T:Position" /> object from which to take the new <see cref="X" /> and
        ///     <see cref="Y" /> values.
        /// </param>
        internal void Set([NotNull] Position<T> newPosition)
        {
            if(_isLocked)
                throw new LockedException("This object is locked.  Changes may only be made by the director.");

            var x = newPosition.X;
            var y = newPosition.Y;

            var xChanged = !Equals(x, _x);
            if(xChanged)
                _x = x;

            var yChanged = !Equals(y, _y);
            if(yChanged)
                _y = y;

            if(xChanged)
                OnPropertyChanged("X");
            if(yChanged)
                OnPropertyChanged("Y");
        }
    }
}